/**
 * 详情对话框
 */
var StoragePutSingleInfoDlg = {
    data: {
    	positionNumber: "",
    }
};
/**
 * 添加或者修改页面
 */
var OrderPutDetailedInfoDlg = {
    data: {
        detailedGoodsname: "",
        detailedGoodsnum: "",
        goodsNumber: "",
		goodsNo:"",
        detailedRebubbles: "",
        detailedPacking: "",
        detailedLargeclass: "",
        detailedGoodstype: "",
        detailedPutcondition: "",
        detailedPiecenum: "",
        goodsWeight: "",
        goodsVolume: "",
    }
};

var inputlist = []
var submit = 2
layui.use(['table', 'admin', 'ax','form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var form = layui.form;

    /**
     * 云仓库存表管理
     */
    var ToolStorageStock = {
        tableId: "toolStorageStockTable"
    };

    /**
     * 初始化表格的列
     */
    ToolStorageStock.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键'},
            {field: 'operateName', sort: true, title: '项目'},
            {field: 'customerName', sort: true, title: '客户'},
            {field: 'warehouseName', sort: true, title: '仓库'},
            {field: 'areaNumber', sort: true, title: '库区'},
            {field: 'positionNumber', title: '库位', style:'background-color: #ecf5ff;font-weight: 600;' , sort: true},
            {field: 'goodsName', title: '商品', style:'background-color: #dbf1e1;font-weight: 600;', width:270, event: 'checkbox'},
            {field: 'goodsNumber', title: '编号', sort: true, style:'background-color: #dbf1e1;font-weight: 600;', totalRowText: '合计：', event: 'checkbox'},
            {field: 'num', title: '数量', sort: true, style:'background-color: #dbf1e1;font-weight: 600;', totalRow: true, event: 'checkbox'},
            {field: 'shiftNum', title: '<i class="layui-icon">&#xe642;</i>移库数', totalRow: true,edit:'text'},
            {field: 'editNum', title: '<i class="layui-icon">&#xe642;</i>修正数', totalRow: true,edit:'text'},
            {field: 'stockWeight', sort: true, title: '重量', totalRow: true},
            {field: 'stockVolume', sort: true, title: '体积', totalRow: true},
            {field: 'unitprice', sort: true, title: '单价'},
            {field: 'stockMoney', sort: true, title: '金额', totalRow: true},
            {field: 'goodsUnit', sort: true, title: '单位'},
            {field: 'goodsSpecs', sort: true, title: '规格'},
        ]];
    };

    /**
     * 点击查询按钮
     */
    ToolStorageStock.search = function () {
        var queryData = {};
        queryData['operateId'] = $("#operateId").val();
        queryData['customerId'] = $("#customerId").val();
        queryData['warehouseId'] = $("#warehouseId").val();
        queryData['areaId'] = $("#areaId").val();
        queryData['positionNumber'] = $("#positionNumber").val();
        queryData['goodsNumber'] = $("#goodsNumber").val();
        queryData['goodsName'] = $("#goodsName").val();
        table.reload(ToolStorageStock.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };
	    
	//批量删除
    $('#btnRevoke').click(function () {
    	var checkStatus = table.checkStatus('toolStorageStockTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
            	ids.push(data[i].id);
			}
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/toolStorageStock/btnGroupRevoke?ids="+ids, function (data) {
	                if(data.success){
	                	Feng.success("删除成功!");
	                	table.reload(ToolStorageStock.tableId);
	                } else {
	                    Feng.error("删除失败!" + data.message + "!");
	                }
                }, function (data) {
                    Feng.error("删除失败!" + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("是否删除选中明细?", operation);
		} else {
			layer.alert('请至少选中一条数据');
		}
    });

     //批量移库
     $('#btnShift').click(function () {
    	var checkStatus = table.checkStatus('toolStorageStockTable');
        data = checkStatus.data;
        if (data.length>0) {
            for (var i = 0; i < data.length; i++) {
				if(isNaN(data[i].shiftNum)||data[i].shiftNum == ""){
		    		layer.msg('请输入正确移库数'); 
					return
				}
				if(parseFloat(data[i].shiftNum) <= 0){
					continue
				}
				let obj = {}
				obj.id = data[i].id
				obj.shiftNum = data[i].shiftNum
				inputlist.push(obj)
			}
			submit = 2
	        layer.open({
	            type: 2,
	            title: '选择目的地',
	            area: ['850px', '650px'],
	            anim: 5,
	            content: Feng.ctxPath + '/toolStorageStock/tobtnShift',
	            end: function () {
					if(submit == 1){
						inputlist = []
                		table.reload(ToolStorageStock.tableId);
					}
	            }
	        });
		} else {
			layer.alert('请至少勾选一条商品');
		}
     });

     //批量移库明细查询
     $('#btnShiftQuery').click(function () {
        layer.open({
            type: 2,
            title: '批量移库明细查询',
            area: ['1200px', '550px'],
            anim: 5,
            content: Feng.ctxPath + '/toolBtnShift',
            end: function () {
            }
        });
     });
		 
	//拉取聚水潭拣货暂存位调入明细
    $('#pulljstzcPutDetailed').click(function () {
        layer.open({
            type: 2,
            title: '拉取聚水潭拣货暂存位调入明细',
            area: ['850px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/toolStorageStock/topulljstzcPutDetailed',
            end: function () {
                table.reload(ToolStorageStock.tableId);
            }
        });
    });
		 
	//拉取聚水潭拣货、通用暂存位库存
    $('#pulljststorageStock').click(function () {
        layer.open({
            type: 2,
            title: '拉取聚水潭拣货、通用暂存位库存',
            area: ['850px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/toolStorageStock/topulljststorageStock',
            end: function () {
                table.reload(ToolStorageStock.tableId);
            }
        });
    });
    
    // 导入excel
    $('#btnExpimport').click(function () {
        layer.open({
            type: 2,
            title: '库存导入',
            area: ['1000px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/toolStorageStock/toimportExcel',
            end: function () {
                table.reload(ToolStorageStock.tableId);
            }
        });
    });

    /**
     * 弹出添加对话框
     */
    ToolStorageStock.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/toolStorageStock/add';
    };

    /**
     * 导出excel按钮
     */
    ToolStorageStock.exportExcel = function () {
        var checkRows = table.checkStatus(ToolStorageStock.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + ToolStorageStock.tableId,
        url: Feng.ctxPath + '/toolStorageStock/list',
        page: true,
        limit: 120,
		limits:[60,120,240,360,480,1500,5000,10000,20000,80000],
        height: "full-60",
        toolbar: '#toolbarfrom',
        cellMinWidth: 100,
        totalRow: true ,//开启合计行
        cols: ToolStorageStock.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        ToolStorageStock.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        ToolStorageStock.openAddDlg();
    });

    // 导出excel
    $('#btnExp').click(function () {
        ToolStorageStock.exportExcel();
    });

    // 单击行事件
    table.on('row(' + ToolStorageStock.tableId + ')', function (obj) {
		$('div[lay-id="' + ToolStorageStock.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
		$('div[lay-id="' + ToolStorageStock.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6;" });//改变当前tr颜色
    });

    // 编辑单元格 事件
    table.on('edit(' + ToolStorageStock.tableId + ')', function (obj) {
        var data = obj.data;//得到所在行所有键值
		var value = obj.value;//修改后的值
		if(isNaN(value)||value == ""){
    		layer.msg('请输入正确数值'); 
			return
		}
		if(obj.field == "editNum"){
	        var ajax = new $ax(Feng.ctxPath + "/toolStorageStock/editGroupsStock?id="+data.id+"&num="+value, function (data) {
	    		if (data.success) {
	                Feng.success("修改成功!");
	        		table.reload(ToolStorageStock.tableId);
				} else {
	                Feng.error("修改失败！"+data.message);
				}
	        }, function (data) {
	            Feng.error("修改失败!" + data.responseJSON.message + "!");
	        });
	        ajax.start();
		}
		if(obj.field == "shiftNum"){
			if(parseFloat(value) > parseFloat(data.num)){
	    		layer.msg('超出库存数量'); 
				return
			}
		}
    });

    //点击选择库位
    $('#choicep').click(function () {
        layer.open({
            type: 2,
            title: '选择库位',
            area: ['900px', '500px'],
            content: Feng.ctxPath + '/storagePutSingle/toPositionStock?positionAreaId='+$("#areaId").val()+'&warehouseId='+$("#warehouseId").val(),
            end: function () {
                $("#positionNumber").val(StoragePutSingleInfoDlg.data.positionNumber);//库位编号
            }
        });
    });
    
    //点击选择商品名称
    $('#choiceg').click(function () {
    	var customerId = $("#customerId").val();
    	if (customerId==null||customerId=='') {
    		layer.msg('Please Select Customer'); 
		} else {
	        layer.open({
	            type: 2,
	            title: '选择商品',
	            area: ['900px', '500px'],
	            content: Feng.ctxPath + '/orderPutDetailed/toChoiceGoods?goodsCustomerId=' + customerId,
	            end: function () {
	                $("#goodsName").val(OrderPutDetailedInfoDlg.data.detailedGoodsname);//商品名称
	                $("#goodsNumber").val(OrderPutDetailedInfoDlg.data.goodsNumber);//商品编号
	            }
	        });
		}
    });
    
    //查询库区
    form.on('select(warehouseId)',function(){
    	$("#areaId").empty();
    	$.ajax({
    		url:Feng.ctxPath + '/basicArea/Querylist',
    	    dataType:"json",   //返回格式为json
    	    async: false,
    	    data:{"areaWarehouseId":$("#warehouseId").val()},    //参数值
    	    type:"post",   //请求方式
    	    success:function(data){
    	        if(data.length>0){
    	        	var str = "<option value=''>选择库区</option>";
    	        	$.each(data,function(key,value){
    	        		str += "<option value='"+value.id+"'>"+value.areaName+"</option>";
    	        	});
    	        	$("#areaId").html(str);
    	        }
    	    }
    	});
        form.render('select');
    });

});
